package com.bs.manager04.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.manager04.entity.Menu;
import com.bs.manager04.entity.Role;
import com.bs.manager04.entity.User;
import com.bs.manager04.mapper.UserMapper;
import com.bs.manager04.service.IMenuService;
import com.bs.manager04.service.IRoleService;
import com.bs.manager04.utils.exception.NotUserException;
import com.bs.manager04.utils.security.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager04.service.impl
 * @ClassName:UserDetailServiceImpl
 * @Descirption:
 * @data 2022/12/21 20:29
 */
//创建UserDetailServiceImpl类，重写方法，操作根据用户名查询用户信息
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    //注入mapper类
    @Resource
    UserMapper mapper;

    @Resource
    IRoleService roleService;

    @Resource
    IMenuService menuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询该用户信息
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.eq(User::getUsername,username);
        User user = mapper.selectOne(lq);
        //获取登录用户的所有角色
        List<Role> roles = roleService.addRoles(user.getUserid());
        user.setRoles(roles);
        //获取登录用户的菜单列表（以树形结构展示）
        List<Menu> menus = menuService.addMenus(user.getUserid(), "0");
        user.setMenus(menus);
        //获取登录用户的所有权限
        List<String> premission = menuService.addPremission(user.getUserid());
        Set<String> set=new HashSet<>(premission);
        user.setPremission(set);
        //如果该用户不存在，提示用户异常信息
        if(user==null){
            throw new NotUserException("用户名或密码错误");
        }

        return new LoginUser(user);
    }
}
